import React, { useState, useEffect, useCallback } from 'react';
import { Modal, Form, Input, Select, Cascader, Radio, Button, message } from 'antd';
import styles from '../styles.less';
import { IAllProps } from '@/typings/types';
import { getCollegeList } from '@/services/basic/college';
import { CascaderValueType } from 'antd/lib/cascader';
import { saveStudentInfo, getspecialtyList, updateStudentInfo } from '@/services/basic/student';
import { getSchoolFacultyListBySchoolId, getClassList } from '@/services/basic/class_and_grade';
import { ISaveStudentParams, IUpdateStudentParams } from '@/typings/student';
interface CreateFormProps {
  modalVisible: boolean;
  type: string;
  willEditStudent: IAllProps;
  refreshList: () => void;
  onCancel: () => void;
}

const addressOptions = [
  {
    value: '浙江',
    label: '浙江',
    children: [
      {
        value: '杭州',
        label: '杭州',
      },
    ],
  },
  {
    value: '江苏',
    label: '江苏',
    children: [
      {
        value: '南京',
        label: '南京',
      },
    ],
  },
];

const CreateForm: React.FC<CreateFormProps> = (props) => {
  const [form] = Form.useForm();

  const { modalVisible, willEditStudent, refreshList, onCancel } = props;
  const [academyList, setAcademyList] = useState([]);
  const [schoolFacultyList, setSchoolFacultyList] = useState([]);
  const [schoolSpecialtyList, setSchoolSpecialtyList] = useState([]);
  // const [nativeList, setNativeList] = useState([]);
  const [classList, setClassList] = useState([]);
  const [selectedAddress, setSelectedAddress] = useState<CascaderValueType>([]);

  const handleReset = ()=>{
    form.resetFields();
    onCancel();
    refreshList();
  }

  //新增
  const handleSumbit = async (values: IAllProps) => {
    //处理地理位置的格式
    const realStudentPlace = `${values.studentPlace[0]},${values.studentPlace[1]}`; 
    if (Object.keys(willEditStudent).length > 0) {
      const {
        studentName,
        studentSex,
        classMsgId,
        schoolSpecialId,
        studentPractice,
        studentStatus,
        studentNumber,
        schoolId,
        schoolFacultyId,
      } = values;
      const params: IUpdateStudentParams = {
        id: willEditStudent.id,
        studentName,
        studentSex,
        classMsgId,
        majorId: willEditStudent.majorId,
        studentPractice,
        studentStatus,
        studentNumber,
        studentPlace:e,
        schoolId,
        schoolFacultyId,
        schoolSpecialId
      };

      const updateResult = await updateStudentInfo(params)
      // console.log(updateResult)

      if (updateResult.code === 0) {
        handleReset()
        message.success('修改成功');
      } else {
        message.error('修改失败');
      }
      return
    } 
    const result = await saveStudentInfo({
      ...values,
      studentPlace: realStudentPlace,
      majorId: values.schoolSpecialId,
    } as ISaveStudentParams);
    if (result.code === 0) {
      // 清空表单,隐藏模态框
      handleReset()
      message.success('添加成功');
    } else {
      message.error('添加失败');
    }
  };

  const handleHidden = () => {
    form.resetFields();
    onCancel();
  };

  //获取院校
  const handleSchoolChange = useCallback(async (value: string) => {
    const result = await getSchoolFacultyListBySchoolId(value);
    const { code, data } = result;
    if (code === 0) {
      setSchoolFacultyList(data);
    }
  }, []);

  //获取专业信息
  const handleSchoolFacultyChange = useCallback(async (value: string) => {
    const result = await getspecialtyList(value); 
    const { code, data } = result;
    if (code === 0) {
      setSchoolSpecialtyList(data);
    }
  }, []);

  const handleSpecialChange = useCallback(async (value: string) => {
    const { schoolFacultyId, schoolSpecialId } = form.getFieldsValue();
    const result = await getClassList({ schoolFacultyId, schoolSpecialId });
    const { code, rows } = result;
    if (code === 0) {
      setClassList(rows);
    } 
  }, []);

  useEffect(() => {
    (async () => {
      const params: IAllProps = {};
      if (selectedAddress.length > 0) {
        params.province = selectedAddress[0];
        params.city = selectedAddress[1];
      }
      const result = await getCollegeList(params);
      // console.log(params);

      const { code, data } = result;
      if (code === 0) {
        setAcademyList(data);
      } 
    })();
  }, [selectedAddress]);

  useEffect(() => {
    // 如果不是空对象,说明是编辑状态
    if (Object.keys(willEditStudent).length > 0) {
      const {
        schoolId,
        schoolFacultyId,
        specialId,
        studentName,
        studentSex,
        studentNumber,
        classMsgId,
        studentStatus,
        studentPractice,
        studentPlace,
      } = willEditStudent; 
      handleSchoolChange(schoolId);
      handleSchoolFacultyChange(schoolFacultyId);
      handleSpecialChange(specialId);
      // 设置初始值
      form.setFieldsValue({
        studentName,
        studentSex,
        studentNumber,
        classMsgId,
        studentStatus,
        schoolId,
        schoolFacultyId,
        specialId,
        studentPractice,
        studentPlace: studentPlace.split(','),
      });
    }
  }, [willEditStudent, handleSchoolChange, handleSchoolFacultyChange, handleSpecialChange]);

  return (
    <Modal
      destroyOnClose
      title="新增学生"
      visible={modalVisible}
      onCancel={handleHidden}
      footer={null}
    >
      <Form
        form={form}
        name="基础信息"
        className={styles.form}
        onFinish={handleSumbit}
      >
        <Form.Item
          name="studentName"
          label="学生姓名"
          rules={[{ required: true, message: '学生姓名必须写！' }]}
        >
          <Input placeholder="请输入学生姓名" />
        </Form.Item>
        <Form.Item
          name="studentSex"
          label="性别"
          rules={[{ required: true, message: '请选择性别！' }]}
        >
          <Radio.Group>
            <Radio value={1}>男</Radio>
            <Radio value={0}>女</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item
          name="studentNumber"
          label="学号"
          rules={[
            { required: true, message: '学生学号必须写！' },
            // {pattern:/^\d{9}$/}
          ]}
        >
          <Input placeholder="请输入学生学号" />
        </Form.Item>
        <Form.Item
          name="classMsgId"
          label="班级"
          rules={[{ required: true, message: '学生班级必须写！' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name="studentStatus"
          label="学籍状态"
          hasFeedback
          rules={[{ required: true, message: '学籍状态必须选！' }]}
        >
          <Select placeholder="选择学籍状态">
            <Select.Option value="在校">在校 </Select.Option>
            <Select.Option value="离校">离校 </Select.Option>
            <Select.Option value="休学">离校 </Select.Option>
            <Select.Option value="毕业">离校 </Select.Option>
            <Select.Option value="退学">离校 </Select.Option>
            <Select.Option value="辍学">离校 </Select.Option>
            <Select.Option value="入伍">离校 </Select.Option>
            <Select.Option value="延长学制">离校 </Select.Option>
          </Select>
        </Form.Item>
        <Form.Item>
          <Form.Item name="schoolId" label="学校" rules={[{ required: true, message: '学校' }]}>
            <Select onChange={handleSchoolChange} className={styles.schoolSelect}>
              {academyList.map((a: IAllProps, index) => (
                <Select.Option value={a.schoolId} key={index}>
                  {a.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="schoolFacultyId"
            label="院系"
            rules={[{ required: true, message: '院系必选！' }]}
          >
            <Select onChange={handleSchoolFacultyChange} className={styles.schoolSelect}>
              {schoolFacultyList.map((s: IAllProps) => (
                <Select.Option value={s.facultyId} key={s.facultyId}>
                  {s.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="schoolSpecialId"
            label="专业"
            rules={[{ required: true, message: '专业必选！' }]}
          >
            <Select onChange={handleSpecialChange} className={styles.schoolSelect}>
              {schoolSpecialtyList.map((a: IAllProps) => (
                <Select.Option value={a.specialId} key={a.specialId}>
                  {a.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
        </Form.Item>

        <Form.Item
          name="studentPractice"
          label="类型"
          rules={[{ required: true, message: '请选择主修或辅修！' }]}
        >
          <Radio.Group>
            <Radio value="主修">主修</Radio>
            <Radio value="辅修">辅修</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item
          name="studentPlace"
          label="籍贯"
          rules={[{ required: true, message: '籍贯必须选！' }]}
        >
          <Cascader options={addressOptions} placeholder="请选择学生籍贯" />
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit" className={styles.createButton}>
            提交
          </Button>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default CreateForm;
